package main

import (
	"context"
	"github.com/golang/protobuf/proto"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	hello2 "grpc-generic/example/api/hello"
	"grpc-generic/pkg/grpc/generic"
	"grpc-generic/pkg/utils/logger"
)

func main() {
	call()
	callGeneric()
}

func getServerConn() *grpc.ClientConn {
	conn, err := grpc.Dial("127.0.0.1:8888",
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy":"round_robin"}`),
	)
	if err != nil {
		panic(err)
	}
	return conn
}

// call 正常调用
func call() {
	conn := getServerConn()
	client := hello2.NewHelloClient(conn)
	res, err := client.SayHello(context.Background(), &hello2.HelloReq{Uid: "10001", Message: "hello server"})
	if err != nil {
		panic(err)
	}
	logger.Infof("response: %+v", res)
}

// callGeneric 泛化调用
func callGeneric() {
	ctx := context.Background()
	conn := getServerConn()
	client := generic.NewGpcGenericClient(hello2.Hello_ServiceDesc.ServiceName, conn)
	if err := client.Init(ctx); err != nil {
		logger.Error("grpc generic client init error: ", err)
		return
	}

	// json 请求体调用
	res1, err := client.InvokeUnaryJson(ctx, "SayHello", map[string]interface{}{"uid": "1001", "message": "json"})
	if err != nil {
		panic(err)
	}
	logger.Infof("generic InvokeUnaryJson res: %v", res1)

	// protobuf bytes 请求体调用
	req := &hello2.HelloReq{Uid: "1001", Message: "protobuf req"}
	protoBytes, err := proto.Marshal(req)
	if err != nil {
		panic(err)
	}
	res2, err := client.InvokeUnary(ctx, "SayHello", protoBytes)
	if err != nil {
		panic(err)
	}
	logger.Infof("generic InvokeUnary res: %v", res2)
}
